package com.lyt.mall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.lyt.common.constant.AuthConstant;
import com.lyt.common.utils.HttpUtils;
import com.lyt.common.utils.R;
import com.lyt.common.vo.MemberVO;
import com.lyt.mall.auth.feign.MemberFeignService;
import com.lyt.mall.auth.vo.SocialUserVO;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: LiuYutong
 */
@Controller
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @RequestMapping("/oauth/weibo/success")
    public String weiboOAuth(@RequestParam("code") String code, HttpSession session, HttpServletResponse response) throws Exception {
        Map<String,String> body = new HashMap<>();
        body.put("client_id","1545422222");
        body.put("client_secret","298e0e3bce0592595a0b0cffc7ad9f3d");
        body.put("grant_type","authorization_code");
        body.put("redirect_uri","http://auth.lyt.com/oauth/weibo/success");
        body.put("code",code);
        //根据code获取对应的Token信息
        HttpResponse post = HttpUtils.doPost("https://api.weibo.com"
                , "/oauth2/access_token"
                , "post"
                , new HashMap<>()
                , null
                , body
        );
        int statusCode = post.getStatusLine().getStatusCode();
        if (statusCode != 200){
            //说明获取Token失败，调回到登录页面
            return "redirect:http://auth.lyt.com/login.html";
        }
        ////说明获取Token成功
        String json = EntityUtils.toString(post.getEntity());
        SocialUserVO socialUserVO = JSON.parseObject(json, SocialUserVO.class);
        R r = memberFeignService.socialLogin(socialUserVO);
        if (r.getCode() != 0){
            //登录错误
            return "redirect:http://auth.lyt.com/login.html";
        }
        String entityJson = (String) r.get("entity");
        MemberVO memberVO = JSON.parseObject(entityJson, MemberVO.class);
        session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
        //注册成功需要跳转到商城首页
        return "redirect:http://mall.lyt.com/home";
    }
}
